const Runtime = require('../runtime/index')
const SessionStore = Runtime.SessionStore
const config = Runtime.App.AppConfig.runtime.sso
const crypto = require('crypto')

function md5Sign() {
  let args = Array.prototype.slice.call(arguments, 0)
  let source = ''
  args.forEach(item => {
    source += item
  })
  source = source + config.md5
  const hash = crypto.createHash('md5')
  hash.update(source)
  return hash.digest('hex')
}

module.exports = {
  getTokenAsync(code) {
    let sign = md5Sign(code)
    let httpClient = new Runtime.App.HttpClient({
      httpHost: config.host,
      urlPath: '/api/caas/auth',
      queryParams: {
        code: code,
        sign: sign
      }
    })
    return httpClient
      .get()

  },
  /**
   * 获取用户可访问资源清单
   * @param {any} sessionId
   * @param {any} token
   * @param {obj} resourcesObj
   * @param {obj} operationsObj
   * @returns
   */
  getUserResourcesAsync(sessionId, token,resourcesObj,operationsObj) {
    let sign = md5Sign(sessionId, token)
    console.log('lxf--',resourcesObj)
    let httpClient = new Runtime.App.HttpClient({
      httpHost: config.host,
      urlPath: '/api/caas/getResources',
      formData: {
        sessionId: sessionId,
        resourcesObj:resourcesObj,
        operationsObj:operationsObj,
        token: token,
        sign: sign
      }
    })
    return httpClient
      .post()
  },
  /**
   * 获取用户可访问资源清单
   * @param {any} token
   * @returns
   */
  checkSessionAsync(sessionId, token) {
    let sign = md5Sign(sessionId, token)
    let httpClient = new Runtime.App.HttpClient({
      httpHost: config.host,
      urlPath: '/api/caas/session',
      queryParams: {
        sid: sessionId,
        token: token,
        sign: sign
      }
    })
    return httpClient
      .get()
  },
  logoutAsync(sessionId, token) {
    let sign = md5Sign(sessionId, token)
    let httpClient = new Runtime.App.HttpClient({
      httpHost: config.host,
      urlPath: '/api/caas/logout',
      queryParams: {
        sid: sessionId,
        token: token,
        sign: sign
      }
    })
    return httpClient
      .get()
  }
}
